package org.example.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.mapper.TasksMapper;
import org.example.pojo.Tasks;
import org.example.service.TasksService;
import org.example.utils.PageBean;
import org.example.utils.R;
import org.example.utils.TasksResponseData;
import org.example.ws.TaskNotify;
import org.springframework.stereotype.Service;
import java.util.Comparator;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: TasksServiceImpl
 * Description:
 *
 * @Author Kotaro
 * @Create 2024/11/26 16:22
 * @Version 1.0
 */
@Service
public class TasksServiceImpl implements TasksService {

    @Resource
    private TasksMapper tasksMapper;
    @Override
    public R selectTasksStatusByRequesterId(Tasks tasks) {
        try {
            // 执行插入操作
            tasksMapper.addTask(tasks);
            List<TasksResponseData> tasksResponseData = tasksMapper.selectTasksByRequesterId(tasks.getRequesterId());
            return R.successful("发布成功！请耐心等待社区审核！",tasksResponseData);
        } catch (Exception e) {
                return R.error("重复任务：相同任务内容、类别和标题的任务已存在", null);
        }
    }

    @Override
    public R selectTasksStatusByReceiverId(String receiverId, Integer taskId) {
        Integer taskStatus = tasksMapper.selectTasksStatusByReceiverId(receiverId);

        //如果该志愿者一次任务都没接过，根据它的id查不出任务状态情况
        if(taskStatus == null){
            int rows = tasksMapper.updateReceiverIdByTasksId(receiverId , taskId);
            if(rows > 0){
                return R.successful("接受成功，请及时与老人取得联系",null);
            }
            return R.error("接受失败",null);
        }

        //每个志愿者一次性只能接一个任务
        if(taskStatus == 1){
            return R.error("您还有一条任务正在预约中，暂时无法接受其他任务",null);
        }else if(taskStatus == 2){
            return R.error("您还有一条任务正在进行中，暂时无法接受其他任务",null);
        }else {
            int rows = tasksMapper.updateReceiverIdByTasksId(receiverId , taskId);
            if(rows > 0){
                return R.successful("接受成功，请及时与老人取得联系",null);
            }
            return R.error("接受失败",null);
        }
    }

    @Override
    public R selectTasksBytaskStatus(String taskStatus) {
        Tasks tasks = tasksMapper.selectTasksByTasksStatus(taskStatus);

        return null;
    }

    @Override
    public R reviewTasksByTasksId(Integer taskId, Integer rating, String comment) {
        int rows = tasksMapper.reviewTasksByTasksId(taskId , rating , comment);
        if(rows > 0){
            return R.successful("感谢您的评价，欢迎您下次继续使用",null);
        }
        return R.error("评价失败",null);
    }

    @Override
    public R completeTasksByTasksId(Integer taskId) {
        int rows = tasksMapper.completeTasksByTasksId(taskId);
        if(rows > 0){
            return R.successful("感谢您的志愿服务，请耐心等待老人评价",null);
        }
        return R.error("完成失败",null);
    }

//    @Override
//    public R showAllTasks(Integer taskCategory) {
//        List<Tasks> tasks = tasksMapper.showAllTasks(taskCategory);
//        return null;
//    }

    @Override
    public R page(int pageSize, int currentPage, Integer taskCategory) {
        //分页
        PageHelper.startPage(currentPage,pageSize);
        //查询
        List<Tasks> tasks = tasksMapper.showAllTasksByTaskCategory(taskCategory);

        if(tasks == null){
            return R.error("查询失败",null);
        }

        // 通过Topsis的思想进行排序，首先按照自定义的优先级排序，再按照预约时间排序
        tasks = tasks.stream()
                .sorted(Comparator
                        // 优先排序：独居且无法自理的老人优先
                        .comparing((Tasks task) -> (task.getSelfCare() == false && task.getIsLivingAlone() == true) ? 0 : 1) // 独居且无法自理优先
                        .thenComparing((Tasks task) -> (task.getSelfCare() == false) ? 0 : 1) // 无法自理优先
                        .thenComparing((Tasks task) -> (task.getIsLivingAlone() == true) ? 0 : 1) // 独居优先
                        // 最后按预约时间排序，越早越前
                        .thenComparing(Tasks::getAppointmentTime, Comparator.nullsLast(Comparator.naturalOrder())) // 按预约时间排序，null值排最后
                )
                .collect(Collectors.toList());

        //分页数据装配
        PageInfo<Tasks> info = new PageInfo<>(tasks);

        //装配PageBean
        PageBean<Tasks> pageBean = new PageBean<>(currentPage , pageSize , info.getTotal() , info.getList());

        R successful = R.successful("查询成功", pageBean);
        return successful;
    }

    @Override
    public R pageByString(int pageSize, int currentPage, String userId) {
        //分页
        PageHelper.startPage(currentPage,pageSize);
        //查询
        List<Tasks> tasks = tasksMapper.showAllTasksByUserId(userId);

        if(tasks == null){
            return R.error("查询失败",null);
        }

        // 排序：任务状态为 0 的任务排在最前，其他根据状态和创建时间排序
        tasks.sort((task1, task2) -> {
            // 首先按任务状态排序：任务状态为 0 的任务排在前面
            if (task1.getTaskStatus() == 0 && task2.getTaskStatus() != 0) {
                return -1; // task1 排在前
            }
            if (task2.getTaskStatus() == 0 && task1.getTaskStatus() != 0) {
                return 1;  // task2 排在前
            }

            // 如果任务状态相同，按创建时间排序：注意处理 null 值
            if (task1.getTaskStatus() == task2.getTaskStatus()) {
                // 如果创建时间为 null，则排在最后
                Date createdAt1 = task1.getCreatedAt();
                Date createdAt2 = task2.getCreatedAt();

                if (createdAt1 == null && createdAt2 != null) {
                    return 1;  // task1 排在后面
                } else if (createdAt2 == null && createdAt1 != null) {
                    return -1; // task1 排在前面
                } else if (createdAt1 == null && createdAt2 == null) {
                    return 0; // 两者都是 null，认为相等
                }
                // 都有创建时间时，按创建时间升序排序
                return createdAt1.compareTo(createdAt2);
            }

            // 按任务状态升序排序
            return Integer.compare(task1.getTaskStatus(), task2.getTaskStatus());
        });

        //分页数据装配
        PageInfo<Tasks> info = new PageInfo<>(tasks);

        //装配PageBean
        PageBean<Tasks> pageBean = new PageBean<>(currentPage , pageSize , info.getTotal() , info.getList());

        R successful = R.successful("查询成功", pageBean);
        return successful;
    }

    @Override
    public R recallTasksByTaskId(Integer taskId) {
        int rows = tasksMapper.recallTasksByTaskId(taskId);
        if(rows > 0){
            return R.successful("撤销成功",null);
        }
        return R.error("撤销失败",null);
    }

    @Override
    public R pageByStringAndInteger(int pageSize, int currentPage, String userId, Integer taskStatus) {
        //分页
        PageHelper.startPage(currentPage,pageSize);
        //查询
        List<Tasks> tasks = tasksMapper.showAllTasksByStringAndInteger(userId , taskStatus);

        if(tasks == null){
            return R.error("查询失败",null);
        }
        //分页数据装配
        PageInfo<Tasks> info = new PageInfo<>(tasks);

        //装配PageBean
        PageBean<Tasks> pageBean = new PageBean<>(currentPage , pageSize , info.getTotal() , info.getList());

        R successful = R.successful("查询成功", pageBean);
        return successful;
    }
}
